package com.blue.alipay.controller;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.*;
import com.alipay.api.internal.util.json.JSONWriter;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.blue.alipay.contants.Alipay2;
import com.blue.alipay.contants.AlipayConfig;
import com.blue.alipay.utils.controller.BaseController;
import com.blue.alipay.utils.date.DateUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;


/**
 * 描述 阿里 h5 支付
 * 时间 2017-6-21 11:10
 * 作者 肖亦鸣
 */
@Controller
@RequestMapping("wappay")
public class AliWapPayController extends BaseController {
    private static Logger logger = LogManager.getLogger(AliWapPayController.class.getName());


    private final String PATH = "wappay/";

    @RequestMapping("index.html")
    public String index() throws Exception {
        logger.info("index...");
        return PATH + "index";
    }

    @RequestMapping("pay.html")
    public String pay() throws Exception {
        logger.info("pay...");
        return PATH + "pay";
    }

    @RequestMapping(value = "dopay.html")
    public String doPay() throws Exception {
        logger.info("dopay...");
        logger.info("doPay requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        if (request.getParameter("WIDout_trade_no") != null) {
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 订单名称，必填
            String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"), "UTF-8");
            // 付款金额，必填
            String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"), "UTF-8");
            // 商品描述，可空
            String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");
            logger.info("subject:{},body:{}", subject, body);
            // 超时时间 可空
            String timeout_express = "2m";
            // 销售产品码 必填
            String product_code = "QUICK_WAP_PAY";
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                    AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
                    AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

            // 封装请求支付信息
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(out_trade_no);
            model.setSubject(subject);
            model.setTotalAmount(total_amount);
            model.setBody(body);
            model.setTimeoutExpress(timeout_express);
            model.setProductCode(product_code);
            logger.info("AlipayTradeWapPayModel :{}", JSON.toJSONString(model));
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl(AlipayConfig.notify_url);
            // 设置同步地址
            alipay_request.setReturnUrl(AlipayConfig.return_url);

            // form表单生产
            String form = "";
            try {
                // 调用SDK生成表单,,其实就是内部组装参数
                AlipayTradeWapPayResponse payResponse = client.pageExecute(alipay_request);
                Map<String, String> params = payResponse.getParams();
                logger.info("params :{}", JSON.toJSONString(params));
                form = payResponse.getBody();

                response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
                response.getWriter().write(form);//直接将完整的表单html输出到页面
                response.getWriter().flush();
                response.getWriter().close();
            } catch (AlipayApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return PATH + "pay";
    }

    @RequestMapping("pay_http.html")
    public String payHttp() throws Exception {
        logger.info("pay_http...");
        return PATH + "pay_http";
    }

    @RequestMapping(value = "dopay_http.html")
    public String doPayHttp() throws Exception {
        logger.info("doPayHttp...");
        logger.info("doPayHttp requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        String subject = new String(request.getParameter("WIDsubject"));
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"), "UTF-8");
        String body = new String(request.getParameter("WIDbody"));
        logger.info("subject:{},body:{}", subject, body);
        String timeout_express = "2m";
        String product_code = "QUICK_WAP_PAY";
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);

        SortedMap<String, String> paramMap = new TreeMap<String, String>();
        paramMap.put(AlipayConstants.METHOD, "alipay.trade.wap.pay");
        paramMap.put(AlipayConstants.BIZ_CONTENT_KEY, new JSONWriter().write(model, true));
        paramMap.put(AlipayConstants.VERSION, "2.0");
        paramMap.put(AlipayConstants.APP_ID, Alipay2.APPID);
        paramMap.put(AlipayConstants.SIGN_TYPE, Alipay2.SIGNTYPE);
        paramMap.put(AlipayConstants.NOTIFY_URL, AlipayConfig.notify_url);
        paramMap.put(AlipayConstants.RETURN_URL, AlipayConfig.return_url);
        paramMap.put(AlipayConstants.CHARSET, Alipay2.CHARSET);
        paramMap.put(AlipayConstants.TIMESTAMP, DateUtil.getCurrentDate());
        paramMap.put(AlipayConstants.FORMAT, Alipay2.FORMAT);
        paramMap.put(AlipayConstants.ALIPAY_SDK, AlipayConstants.SDK_VERSION);
        paramMap.put(AlipayConstants.PROD_CODE, product_code);
        String signContent = getSignContent(paramMap);
        paramMap.put(AlipayConstants.SIGN,
                AlipaySignature.rsaSign(signContent, Alipay2.RSA_PRIVATE_KEY, Alipay2.CHARSET, Alipay2.SIGNTYPE));
        String url = getRedirectUrl(paramMap);
        logger.info("url:{}", url);
        response.sendRedirect(url);
        return PATH + "pay_http";
    }

    public static String getSignContent(Map<String, String> sortedParams) {
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<String>(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = sortedParams.get(key);
            if (StringUtils.areNotEmpty(key, value)) {
                content.append((index == 0 ? "" : "&") + key + "=" + value);
                index++;
            }
        }
        return content.toString();
    }

    private String getRedirectUrl(Map<String, String> sortedMap) throws AlipayApiException {
        StringBuffer urlSb = new StringBuffer(AlipayConfig.URL);
        try {
            String sortedQuery = WebUtils.buildQuery(sortedMap, AlipayConfig.CHARSET);
            String sign = sortedMap.get(AlipayConstants.SIGN);
            urlSb.append("?");
            urlSb.append(sortedQuery);
            if (sign != null & sign.length() > 0) {
                Map<String, String> signMap = new HashMap<String, String>();
                signMap.put(AlipayConstants.SIGN, sign);
                String signQuery = WebUtils.buildQuery(signMap, AlipayConfig.CHARSET);
                urlSb.append("&");
                urlSb.append(signQuery);
            }
        } catch (IOException e) {
            throw new AlipayApiException(e);
        }

        return urlSb.toString();
    }

    @RequestMapping("query.html")
    public String query() throws Exception {
        logger.info("query...");
        return PATH + "query";
    }

    @RequestMapping("doquery.html")
    public String doQuery() throws Exception {
        logger.info("doQuery...");
        logger.info("doQuery requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        if (request.getParameter("WIDout_trade_no") != null || request.getParameter("WIDtrade_no") != null) {
            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("WIDtrade_no").getBytes("ISO-8859-1"), "UTF-8");
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeQueryRequest alipay_request = new AlipayTradeQueryRequest();

            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            model.setOutTradeNo(out_trade_no);
            model.setTradeNo(trade_no);
            alipay_request.setBizModel(model);

            AlipayTradeQueryResponse alipay_response = client.execute(alipay_request);
            System.out.println(alipay_response.getBody());
            request.setAttribute("msg", alipay_response.getBody());
            request.setAttribute("WIDout_trade_no", out_trade_no);
            request.setAttribute("WIDtrade_no", trade_no);
        }
        return PATH + "query";
    }

    @RequestMapping("refund.html")
    public String refund() throws Exception {
        logger.info("refund...");
        return PATH + "refund";
    }

    @RequestMapping("dorefund.html")
    public String doRefund() throws Exception {
        logger.info("doDefund...");
        logger.info("doRefund requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        if (request.getParameter("WIDout_trade_no") != null || request.getParameter("WIDtrade_no") != null) {
            //商户订单号和支付宝交易号不能同时为空。 trade_no、  out_trade_no如果同时存在优先取trade_no
            //商户订单号，和支付宝交易号二选一
            String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号，和商户订单号二选一
            String trade_no = new String(request.getParameter("WIDtrade_no").getBytes("ISO-8859-1"), "UTF-8");
            //退款金额，不能大于订单总金额
            String refund_amount = new String(request.getParameter("WIDrefund_amount").getBytes("ISO-8859-1"), "UTF-8");
            //退款的原因说明
            String refund_reason = new String(request.getParameter("WIDrefund_reason").getBytes("ISO-8859-1"), "UTF-8");
            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传。
            String out_request_no = new String(request.getParameter("WIDout_request_no").getBytes("ISO-8859-1"), "UTF-8");
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeRefundRequest alipay_request = new AlipayTradeRefundRequest();

            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(out_trade_no);
            model.setTradeNo(trade_no);
            model.setRefundAmount(refund_amount);
            model.setRefundReason(refund_reason);
            model.setOutRequestNo(out_request_no);
            logger.info("AlipayTradeRefundModel requestParams:{}", JSON.toJSONString(model));
            alipay_request.setBizModel(model);

            AlipayTradeRefundResponse alipay_response = client.execute(alipay_request);
            System.out.println(JSON.toJSONString(alipay_response.getBody()));
            request.setAttribute("msg", alipay_response.getBody());
            request.setAttribute("WIDout_trade_no", out_trade_no);
            request.setAttribute("WIDtrade_no", trade_no);
            request.setAttribute("WIDrefund_amount", refund_amount);
            request.setAttribute("WIDrefund_reason", refund_reason);
            request.setAttribute("WIDout_request_no", out_request_no);
        }
        return PATH + "refund";
    }

    @RequestMapping("refundquery.html")
    public String refundquery() throws Exception {
        logger.info("refundquery...");
        return PATH + "refundquery";
    }

    @RequestMapping("dorefundquery.html")
    public String doRefundQuery() throws Exception {
        logger.info("doRefundQuery...");
        logger.info("doRefundQuery...requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        if (request.getParameter("WIDout_trade_no") != null || request.getParameter("WIDtrade_no") != null && request.getParameter("WIDout_request_no") != null) {
            //商户订单号和支付宝交易号不能同时为空。 trade_no、  out_trade_no如果同时存在优先取trade_no
            //商户订单号，和支付宝交易号二选一
            String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号，和商户订单号二选一
            String trade_no = new String(request.getParameter("WIDtrade_no").getBytes("ISO-8859-1"), "UTF-8");
            //请求退款接口时，传入的退款请求号，如果在退款请求时未传入，则该值为创建交易时的外部交易号
            String out_request_no = new String(request.getParameter("WIDout_request_no").getBytes("ISO-8859-1"), "UTF-8");
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeFastpayRefundQueryRequest alipay_request = new AlipayTradeFastpayRefundQueryRequest();

            AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
            model.setOutTradeNo(out_trade_no);
            model.setTradeNo(trade_no);
            model.setOutRequestNo(out_request_no);
            alipay_request.setBizModel(model);

            AlipayTradeFastpayRefundQueryResponse alipay_response = client.execute(alipay_request);
            System.out.println(alipay_response.getBody());
            request.setAttribute("msg", alipay_response.getBody());
            request.setAttribute("WIDout_trade_no", out_trade_no);
            request.setAttribute("WIDtrade_no", trade_no);
            request.setAttribute("WIDout_request_no", out_request_no);
        }
        return PATH + "refundquery";
    }

    @RequestMapping("close.html")
    public String close() throws Exception {
        logger.info("close...");
        return PATH + "close";
    }

    @RequestMapping("doclose.html")
    public String doClose() throws Exception {
        logger.info("doClose...");
        logger.info("doClose...requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        if (request.getParameter("WIDout_trade_no") != null || request.getParameter("WIDtrade_no") != null) {
            //商户订单号和支付宝交易号不能同时为空。 trade_no、  out_trade_no如果同时存在优先取trade_no
            //商户订单号，和支付宝交易号二选一
            String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号，和商户订单号二选一
            String trade_no = new String(request.getParameter("WIDtrade_no").getBytes("ISO-8859-1"), "UTF-8");
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeCloseRequest alipay_request = new AlipayTradeCloseRequest();

            AlipayTradeCloseModel model = new AlipayTradeCloseModel();
            model.setOutTradeNo(out_trade_no);
            model.setTradeNo(trade_no);
            alipay_request.setBizModel(model);

            AlipayTradeCloseResponse alipay_response = client.execute(alipay_request);
            System.out.println(alipay_response.getBody());
            request.setAttribute("msg", alipay_response.getBody());
            request.setAttribute("WIDout_trade_no", out_trade_no);
            request.setAttribute("WIDtrade_no", trade_no);
        }
        return PATH + "close";
    }

    @RequestMapping("downloadurl.html")
    public String downloadUrl() throws Exception {
        logger.info("downloadUrl...");
        return PATH + "downloadurl";
    }

    @RequestMapping("dodownloadurl.html")
    public String doDownloadUrl() throws Exception {
        logger.info("doDownloadUrl...");
        logger.info("doDownloadUrl...requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        if (request.getParameter("WIDbill_type") != null && request.getParameter("WIDbill_date") != null) {
            // 账单类型，商户通过接口或商户经开放平台授权后其所属服务商通过接口可以获取以下账单类型：trade、signcustomer；
            // trade指商户基于支付宝交易收单的业务账单；signcustomer是指基于商户支付宝余额收入及支出等资金变动的帐务账单；
            String bill_type = new String(request.getParameter("WIDbill_type").getBytes("ISO-8859-1"), "UTF-8");
            // 账单时间：日账单格式为yyyy-MM-dd，月账单格式为yyyy-MM。
            String bill_date = new String(request.getParameter("WIDbill_date").getBytes("ISO-8859-1"), "UTF-8");
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayDataDataserviceBillDownloadurlQueryRequest alipay_request = new AlipayDataDataserviceBillDownloadurlQueryRequest();

            AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
            model.setBillType(bill_type);
            model.setBillDate(bill_date);
            alipay_request.setBizModel(model);

            AlipayDataDataserviceBillDownloadurlQueryResponse alipay_response = client.execute(alipay_request);
            System.out.println(alipay_response.getBillDownloadUrl());
            request.setAttribute("msg", alipay_response.getBillDownloadUrl());
            request.setAttribute("WIDbill_type", bill_type);
            request.setAttribute("WIDbill_date", bill_date);
        }
        return PATH + "downloadurl";
    }

    @RequestMapping(value = "notify_url.html", method = RequestMethod.POST)
    @ResponseBody
    public String notifyUrl() throws Exception {
        logger.info("notify_url...");
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        logger.info("notify_url...requestParams:{}", JSON.toJSONString(requestParams));
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA");
        logger.info("verify_result:{}", verify_result);
        if (verify_result) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                logger.info("notifyUrl success");
                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
        } else {//验证失败
            logger.info("notifyUrl fail");
        }
        //程序执行完后必须打印输出“success”（不包含引号）。如果商户反馈给支付宝的字符不是success这7个字符，支付宝服务器会不断重发通知，直到超过24小时22分钟。
        // 一般情况下，25小时以内完成8次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h）；
        return "success";
    }

    @RequestMapping(value = "return_url.html")
    public String returnUrl() throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        logger.info("returnUrl requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA");

        if (verify_result) {//验证成功
            //请在这里加上商户的业务逻辑程序代码
            //该页面可做页面美工编辑
            request.setAttribute("msg", "success");
            request.setAttribute("returnMsg", JSON.toJSONString(requestParams));
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
        } else {
            //该页面可做页面美工编辑
            request.setAttribute("msg", "fail");
        }
        return PATH + "return_url";
    }
}
